<template>
    <div class="container">
        <Breadcrumb :items="['menu.monitor', 'menu.monitor.alert']" />
        <a-card class="general-card" title=" ">
            <a-row>
                <a-col :flex="1">
                    <a-form
                        :model="formModel"
                        :label-col-props="{ span: 6 }"
                        :wrapper-col-props="{ span: 18 }"
                        label-align="left"
                    >
                        <a-row :gutter="16">
                            <a-col :span="6">
                                <a-form-item
                                    field="alertName"
                                    :label="$t('alert.name')"
                                >
                                    <a-input
                                        v-model="formModel.alertName"
                                        :placeholder="
                                            $t('input.placeholder') +
                                            $t('alert.name')
                                        "
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="6">
                                <a-form-item
                                    field="deviceName"
                                    :label="$t('device.name')"
                                >
                                    <a-input
                                        v-model="formModel.deviceName"
                                        :placeholder="
                                            $t('input.placeholder') +
                                            $t('alert.deviceName')
                                        "
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="6">
                                <a-form-item
                                    field="deviceNo"
                                    :label="$t('alert.deviceNumber')"
                                >
                                    <a-input
                                        v-model="formModel.deviceNo"
                                        :placeholder="
                                            $t('input.placeholder') +
                                            $t('alert.deviceNumber')
                                        "
                                    />
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </a-col>
                <a-divider style="height: 84px" direction="vertical" />
                <a-col :flex="'86px'" style="text-align: right">
                    <a-space direction="vertical" :size="18">
                        <a-button type="primary" @click="search(1)">
                            <template #icon>
                                <icon-search />
                            </template>
                            {{ $t('search') }}
                        </a-button>
                        <a-button @click="reset">
                            <template #icon>
                                <icon-refresh />
                            </template>
                            {{ $t('reset') }}
                        </a-button>
                    </a-space>
                </a-col>
            </a-row>
            <a-divider style="margin-top: 0" />
            <a-row style="margin-bottom: 16px">
                <a-col :span="12">
                    <a-button
                        v-if="selectedKeys.length > 0"
                        type="primary"
                        @click="batDelete(1)"
                    >
                        <template #icon>
                            <icon-delete />
                        </template>
                        {{ $t('delete') }}
                    </a-button>
                </a-col>
                <a-col
                    :span="12"
                    style="
                        display: flex;
                        align-items: center;
                        justify-content: end;
                    "
                >
                    <a-tooltip :content="$t('refresh')">
                        <div class="action-icon" @click="() => search()"
                            ><icon-refresh size="18"
                        /></div>
                    </a-tooltip>
                    <a-tooltip :content="$t('table.column.setting')">
                        <a-popover
                            trigger="click"
                            position="bl"
                            @popup-visible-change="popupVisibleChange"
                        >
                            <div class="action-icon"
                                ><icon-settings size="18"
                            /></div>
                            <template #content>
                                <div id="tableSetting">
                                    <div
                                        v-for="(item, index) in showColumns"
                                        :key="item.dataIndex"
                                        class="setting"
                                    >
                                        <div
                                            style="
                                                margin-right: 4px;
                                                cursor: move;
                                            "
                                        >
                                            <icon-drag-arrow />
                                        </div>
                                        <div>
                                            <a-checkbox
                                                v-model="item.checked"
                                                @change="
                                                    handleChange(
                                                        $event,
                                                        item as TableColumnData,
                                                        index
                                                    )
                                                "
                                            >
                                            </a-checkbox>
                                        </div>
                                        <div class="title">
                                            {{
                                                item.title === '#'
                                                    ? '序列号'
                                                    : item.title
                                            }}
                                        </div>
                                    </div>
                                </div>
                            </template>
                        </a-popover>
                    </a-tooltip>
                </a-col>
            </a-row>
            <a-table
                v-model:selectedKeys="selectedKeys"
                row-key="id"
                :loading="loading"
                :pagination="pagination"
                :columns="(cloneColumns as TableColumnData[])"
                :data="renderData"
                :row-selection="rowSelection"
                :bordered="false"
                :size="size"
                @page-change="onPageChange"
            >
                <template #detail="{ record }">
                    <div
                        v-for="item in record.detail"
                        :key="item"
                        class="detail-number"
                    >
                        {{ item.name }} :<span>{{ item.value }}</span>
                    </div>
                </template>
            </a-table>
        </a-card>
    </div>
</template>

<script lang="ts" setup>
    import { computed, ref, reactive, watch, nextTick } from 'vue';
    import { useI18n } from 'vue-i18n';
    import useLoading from '@/hooks/loading';
    import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
    import pick from 'lodash/pick';
    import Sortable from 'sortablejs';
    import cloneDeep from 'lodash/cloneDeep';
    import { getAlertList, deleteAler } from './service';

    type SizeProps = 'mini' | 'small' | 'medium' | 'large';
    type Column = TableColumnData & { checked?: true };

    const generateFormModel = () => {
        return {
            alertName: '',
            deviceName: '',
            deviceNo: '',
        };
    };

    const rowSelection = reactive({
        type: 'checkbox',
        showCheckedAll: true,
        onlyCurrent: false,
    });
    const selectedKeys = ref([]);

    const { loading, setLoading } = useLoading(true);
    const { t } = useI18n();
    const renderData = ref<any[]>([]);
    const formModel = ref(generateFormModel());
    const cloneColumns = ref<Column[]>([]);
    const showColumns = ref<Column[]>([]);
    const size = ref<SizeProps>('small');

    const pagination = reactive({
        current: 1,
        pageSize: 10,
        total: 0,
    });
    const columns = computed<TableColumnData[]>(() => [
        {
            title: t('alert.name'),
            dataIndex: 'alertName',
        },
        {
            title: t('alert.deviceName'),
            dataIndex: 'deviceName',
        },
        {
            title: t('alert.deviceNumber'),
            dataIndex: 'deviceNo',
        },
        {
            title: t('alert.create.time'),
            dataIndex: 'createTime',
        },
        {
            title: t('alert.detail'),
            dataIndex: 'detail',
            slotName: 'detail',
        },
    ]);
    const fetchData = async (params: any) => {
        setLoading(true);
        try {
            const data = await getAlertList(params);
            renderData.value = data.result.records;
            pagination.total = data.result.total;
        } catch (err) {
            // you can report use errorHandler or other
        } finally {
            setLoading(false);
        }
    };

    const search = (pageNum?: number) => {
        fetchData({
            ...formModel.value,
            current: pageNum || pagination.current,
            size: pagination.pageSize,
        });
    };

    search(1);
    const reset = () => {
        formModel.value = generateFormModel();
        search(1);
    };

    const batDelete = async () => {
        if (selectedKeys.value.length > 0) {
            await deleteAler({ ids: selectedKeys.value });
            search(1);
        }
    };

    const onPageChange = (pageNum: number) => {
        pagination.current = pageNum;
        fetchData({
            size: pagination.pageSize,
            current: pageNum,
        });
    };

    const handleChange = (
        checked: boolean | (string | boolean | number)[],
        column: Column,
        index: number
    ) => {
        if (!checked) {
            cloneColumns.value = showColumns.value
                .filter((item) => item.checked)
                .filter((item) => item.dataIndex !== column.dataIndex);
        } else {
            cloneColumns.value.splice(index, 0, column);
        }
    };

    const exchangeArray = <T extends Array<any>>(
        array: T,
        beforeIdx: number,
        newIdx: number,
        isDeep = false
    ): T => {
        const newArray = isDeep ? cloneDeep(array) : array;
        if (beforeIdx > -1 && newIdx > -1) {
            // 先替换后面的，然后拿到替换的结果替换前面的
            newArray.splice(
                beforeIdx,
                1,
                newArray.splice(newIdx, 1, newArray[beforeIdx]).pop()
            );
        }
        return newArray;
    };

    const popupVisibleChange = (val: boolean) => {
        if (val) {
            nextTick(() => {
                const el = document.getElementById(
                    'tableSetting'
                ) as HTMLElement;
                const sortable = new Sortable(el, {
                    onEnd(e: any) {
                        const { oldIndex, newIndex } = e;
                        exchangeArray(cloneColumns.value, oldIndex, newIndex);
                        exchangeArray(showColumns.value, oldIndex, newIndex);
                    },
                });
            });
        }
    };

    watch(
        () => columns.value,
        (val) => {
            cloneColumns.value = cloneDeep(val);
            cloneColumns.value.forEach((item) => {
                item.checked = true;
            });
            showColumns.value = cloneDeep(cloneColumns.value);
        },
        { deep: true, immediate: true }
    );
</script>

<style scoped lang="less">
    .container {
        padding: 0 20px 20px;
    }

    :deep(.arco-table-th) {
        &:last-child {
            .arco-table-th-item-title {
                margin-left: 16px;
            }
        }
    }

    .detail-number {
        display: inline-block;
        font-size: 14px;

        span {
            padding: 0 10px;
            color: red;
            font-weight: 500;
            font-size: 16px;
            white-space: nowrap;
        }
    }

    .action-icon {
        margin-left: 12px;
        cursor: pointer;
    }

    .active {
        color: #0960bd;
        background-color: #e3f4fc;
    }

    .setting {
        display: flex;
        align-items: center;
        width: 200px;

        .title {
            margin-left: 12px;
            cursor: pointer;
        }
    }
</style>
